﻿using System;
using System.ComponentModel.Composition.Primitives;
using System.Configuration;
using System.Reflection;
using System.Web;

namespace AxeFrog.Composition
{
	public class CatalogManager
	{
		private readonly ComposablePartCatalog _catalog;
		public CatalogManager(params Assembly[] defaultAssemblies)
		{
			string dir;
			if(HttpRuntime.AppDomainAppId != null)
				dir = HttpRuntime.BinDirectory.TrimEnd('\\');
			else
				dir = AppDomain.CurrentDomain.BaseDirectory;
			var cfg = ConfigurationManager.GetSection("extensions") as ExtensionsConfigurationSection;
			var cb = new CatalogBuilder();
			foreach(var asm in defaultAssemblies)
				cb.ForAssembly(asm);


			if(cfg != null)
				foreach(LoadElement load in cfg.Assemblies)
				{
					var path = load.Path.Replace('/', '\\');
					int index = path.LastIndexOf('\\');
					if(index > -1)
						cb.ForAssembliesInDirectory(dir + "\\" + path.Substring(0, index), path.Substring(index + 1));
					else
						cb.ForAssembliesInDirectory(dir, path);
				}

			_catalog = cb.Build();
		}

		public ComposablePartCatalog Catalog
		{
			get { return _catalog; }
		}
	}
}
